package com.cyzy.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cyzy.domain.bean.TUser;
import com.cyzy.domain.bean.TUserAgentMessage;
import com.cyzy.domain.dto.CustomerServiceDto;
import com.cyzy.domain.dto.MessageDto;
import com.cyzy.domain.dto.ResponseData;
import com.cyzy.service.TUserAgentMessageService;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * TODO
 *
 * @author Honarly
 * @date 2024.11.12
 */
@RestController
@RequestMapping("/agent/message")
@RequiredArgsConstructor
public class TUserAgentMessageController {

    private final TUserAgentMessageService tUserAgentMessageService;

    @PostMapping("/init")
    public ResponseData setSession(@RequestBody CustomerServiceDto customerServiceDto, HttpSession session) {
        System.out.println("消息：" + customerServiceDto);
        if (customerServiceDto == null || customerServiceDto.getUserId() == null) {
            return ResponseData.error("error");
        }
        session.setAttribute("currUser", JSONObject.toJSONString(customerServiceDto));
        return ResponseData.success();
    }

    // 客服点击切换用户时，显示对应的聊天记录
    // 用户点击客服选项时，显示对应的聊天记录
    @GetMapping("/getMessage")
    public ResponseData getMessage(Integer userId) {
        System.out.println("userId = " + userId);
        LambdaQueryWrapper<TUserAgentMessage> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TUserAgentMessage::getUserId, userId);
        List<TUserAgentMessage> list = tUserAgentMessageService.list(lqw);
        return ResponseData.success("查询聊天信息成功", list, list.size());
    }

    @PostMapping("/send")
    public ResponseData send(@RequestBody MessageDto message) {
        System.out.println("send: " + message);
        boolean save = tUserAgentMessageService.save(new TUserAgentMessage(message.getToUserId(), message.getMessage(), message.getDirection()));
        if (save) {
            return ResponseData.success("发送消息成功");
        } else {
            return ResponseData.error("发送消息失败");
        }
    }
}
